package com.jf.demo;

import java.util.ArrayList;
import java.util.HashMap;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.GraphicsOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.MyLocationOverlay.LocationMode;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.jf.map.MyOrderMap;
import com.jf.map.NearbyUser;
import com.jf.map.MyOrderMap.MyLocationListenner;
import com.jf.map.MyOrderMap.MyOverlay;
import com.jf.socketMess.MyMessage;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.sys.android.entity.Msg;
import com.sys.android.util.FinalUntil;
import com.sys.android.util.TimeRender;
import com.sys.android.xmppmanager.XmppConnection;

@ContentView(R.layout.my_sendfile_touch)
public class MySendfileTouch extends Activity {

	private int[] messImage = FinalUntil.messImage;

	private String company[] = FinalUntil.company;

	private String alternative[] = { "离我最近", "评价最高" };

//	@ViewInject(R.id.spinner2)
//	private Spinner spinner2;

//	@ViewInject(R.id.spinner1)
//	private Spinner spinner1;

	public ListView vncListView;

	private ArrayList<HashMap<String, Object>> remoteWindowItem;

	private MainmenuList listItemAdapter;

	private SharedPreferences useShare;

	private Double lauY;
	private Double louX;

	public BMapManager mBMapMan;

	// 定位相关
	LocationClient mLocClient;
	XMPPConnection connection = XmppConnection.getConnection();
	private ChatManager cm = connection.getChatManager();
	private String userChat;// 当前聊天 userChat
	private String netWork = FinalUntil.NETWORK;// 网络地址
	Chat newchat;
	private String username;
	public MyLocationListenner myListener = new MyLocationListenner();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mBMapMan = new BMapManager(getApplication());
		mBMapMan.init(null);

		ViewUtils.inject(this);// xml视图加载的处理
		useShare = getSharedPreferences("userInfo", MODE_PRIVATE);
		username = useShare.getString("username", "");
//		ArrayAdapter<String> adspinner2 = new ArrayAdapter<String>(this,
//				android.R.layout.simple_spinner_item, company);
//		adspinner2
//				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//		spinner2.setAdapter(adspinner2);
//
//		ArrayAdapter<String> adspinner1 = new ArrayAdapter<String>(this,
//				android.R.layout.simple_spinner_item, alternative);
//		adspinner1
//				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//		spinner1.setAdapter(adspinner1);

		vncListView = (ListView) findViewById(R.id.listView1);
		remoteWindowItem = new ArrayList<HashMap<String, Object>>();
		listItemAdapter = new MainmenuList(MySendfileTouch.this,
				remoteWindowItem, "操 作");
		vncListView.setAdapter(listItemAdapter);
		vncListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				menuAlert(remoteWindowItem.get(arg2).get("courphone")
						.toString(), remoteWindowItem.get(arg2).get("courName")
						.toString(),remoteWindowItem.get(arg2).get("courierID")
						.toString(),remoteWindowItem.get(arg2).get("brand")
						.toString(),remoteWindowItem.get(arg2).get("company")
						.toString());
			}
		});
		// 定位初始化
		mLocClient = new LocationClient(this);

		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.disableCache(false);
		option.setScanSpan(600000);
		mLocClient.setLocOption(option);
		mLocClient.start();

//		spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
//
//			@Override
//			public void onItemSelected(AdapterView<?> arg0, View arg1,
//					int arg2, long arg3) {
//				// TODO Auto-generated method stub
//
//				// if(arg2>0){
//				//
//				// HashMap<String, Object> map = new HashMap<String, Object>();
//				// map.put("ItemImage",messImage[arg2-1]);//图像资源的ID
//				// map.put("ItemWinName",
//				// company[arg2]+"       10m\n派件员:张军\n15500001234\n服务评价:4.0");
//				// map.put("ItemCloseWin",android.R.drawable.ic_menu_close_clear_cancel);
//				// remoteWindowItem.add(map);
//				//
//				// }else{
//				// for(int i=0;i<5;i++)
//				// {
//				// HashMap<String, Object> map = new HashMap<String, Object>();
//				// map.put("ItemImage",messImage[i]);//图像资源的ID
//				// map.put("ItemWinName",
//				// company[i+1]+"       10m\n派件员:张军\n15500001234\n服务评价:4.0");
//				// map.put("ItemCloseWin",android.R.drawable.ic_menu_close_clear_cancel);
//				// remoteWindowItem.add(map);
//				// }
//				// }
//				// listItemAdapter.notifyDataSetChanged();
//			}
//
//			@Override
//			public void onNothingSelected(AdapterView<?> arg0) {
//				// TODO Auto-generated method stub
//
//			}
//		});

	}

	public void finishTouch(View v) {
		this.finish();
	}

	public void checkMap(View v) {

		Intent intent = new Intent(MySendfileTouch.this, NearbyUser.class);
		startActivity(intent);
	}

	public void locationInit(Double x, Double y) {

		RequestParams params = new RequestParams();
		params.addQueryStringParameter("louX", x.toString());
		params.addQueryStringParameter("lauY", y.toString());

		HttpUtils http = new HttpUtils();
		http.send(HttpMethod.POST, FinalUntil.ServerAddress + "findAround",
				params, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub
						Log.i("MySendfileTouch", arg1);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// arg0.result返回服务器结果
						Log.i("MySendfileTouch", louX + "-" + lauY);
						remoteWindowItem.clear();
						try {
							JSONArray jsonarr = new JSONArray(arg0.result);
							for (int i = 0; i < jsonarr.length(); i++) {
								JSONObject jsonobj = jsonarr.getJSONObject(i);
								GeoPoint p1 = new GeoPoint((int) (lauY * 1E6),
										(int) (louX * 1E6));
								GeoPoint p2 = new GeoPoint((int) (jsonobj
										.getDouble("mapY") * 1E6),
										(int) (jsonobj.getDouble("mapX") * 1E6));
								long mile = Math.round(DistanceUtil
										.getDistance(p1, p2));// 计算距离
								HashMap<String, Object> map = new HashMap<String, Object>();
								map.put("ItemImage",
										messImage[jsonobj.getInt("brand")]);// 图像资源的ID
								map.put("ItemWinName",
										jsonobj.getString("company")
												+ "       " + mile + "m\n派件员:"
												+ jsonobj.getString("realname")
												+ "\n电话:"
												+ jsonobj.getString("username"));
								map.put("ItemCloseWin",
										android.R.drawable.ic_menu_close_clear_cancel);
								map.put("courphone",
										jsonobj.getString("username"));
								map.put("courName",
										jsonobj.getString("realname"));
								map.put("courierID",
										jsonobj.getString("courierID"));
								map.put("brand",
										jsonobj.getString("brand"));
								map.put("company",
										jsonobj.getString("company"));
								remoteWindowItem.add(map);
							}
							listItemAdapter.notifyDataSetChanged();

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;

			lauY = location.getLatitude();
			louX = location.getLongitude();

			locationInit(louX, lauY);
		}

		@Override
		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}

	/**
	 * 菜单信息
	 */
	public void menuAlert(String arg1, String arg2,String arg3,String arg4,String arg5) {
		final String courphone = arg1;
		final String courName = arg2;
		final String courierID = arg3;
		final String brand = arg4;
		final String company = arg5;
		Dialog dialog = new AlertDialog.Builder(this).setTitle("订单操作")
				.setMessage("请在下列菜单中选择操作")
				.setPositiveButton("电话联系", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						Intent intent = new Intent();
						intent.setAction("android.intent.action.CALL");
						intent.setData(Uri.parse("tel:" + courphone));
						startActivity(intent);
					}
				}).setNegativeButton("发 单", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						sendMsg(courphone,courierID,brand,company);
					}
				}).setNeutralButton("消息沟通", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						Intent intent = new Intent();
						intent.putExtra("sendcall", courphone);
						intent.putExtra("sendName", courName);
						intent.setClass(MySendfileTouch.this,
								com.jf.socketMess.MyMessage.class);
						startActivity(intent);
					}
				}).create();
		dialog.show();
	}

	/**
	 * 发送消息
	 * 
	 * @author Administrator
	 * 
	 */
	public void sendMsg(String phone,String courierID,String brand,String company) {
		Intent intent = getIntent();
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("userID", username);
		params.addQueryStringParameter("sendName", intent.getStringExtra("sendName"));
		params.addQueryStringParameter("sendTel", intent.getStringExtra("sendTel"));
		params.addQueryStringParameter("sendAddress", intent.getStringExtra("sendAddress"));
		params.addQueryStringParameter("sendItems", intent.getStringExtra("sendItems"));
		params.addQueryStringParameter("brand", brand);
		params.addQueryStringParameter("company", company);
		params.addQueryStringParameter("courierUserID", courierID);
		params.addQueryStringParameter("states", "3");

		userChat = phone + netWork;
		// 发送消息给pc服务器的好友（获取自己的服务器，和好友）
		newchat = cm.createChat(userChat, null);

		// 发送消息
		try {
			newchat.sendMessage("&新的订单");
			HttpUtils http = new HttpUtils();
			http.send(HttpMethod.POST, FinalUntil.ServerAddress
					+ "releaseOrderTouch", params,
					new RequestCallBack<String>() {

						@Override
						public void onFailure(HttpException arg0, String arg1) {
							// TODO Auto-generated method stub
							Log.i("MySendfileTouch", arg1);
						}

						@Override
						public void onSuccess(ResponseInfo<String> arg0) {
							Toast.makeText(MySendfileTouch.this, "订单发送成功", 0).show();
						}
					});
		} catch (XMPPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
